import React, { useRef } from "react";
import { isNull } from "lodash-es";
import ReactECharts from "echarts-for-react";

const echartsSize = (size, defalteWidth = 1920) => {
  let clientWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth;
  if (!clientWidth) return size;
  let scale = clientWidth / defalteWidth;
  return Number((size * scale).toFixed(3));
};

const Chart4 = React.memo(() => {
  const chartRef = useRef(null);
  const highLightIndexItem = useRef(null);
  const click_type = useRef(null);
  //流程图
  var apis = [
    { uri: "MCA查客户信息", status: 1, axisValue: [0, 80] },
    { uri: "HUB查客户证件", status: 1, axisValue: [0, 20] },
    { uri: "输入资料显示产品信息", status: 1, axisValue: [100, 80] },
    { uri: "输入申购金额", status: 1, axisValue: [200, 80] },
    { uri: "Wealth查新旧资金", status: 0, axisValue: [200, 20] },
    { uri: "MCA查起存条件", status: 1, axisValue: [300, 80] },
    { uri: "录入Vof Rate", status: 1, axisValue: [300, 20] },
    { uri: "输入转出账户", status: 1, axisValue: [400, 80] },
    { uri: "HUB查客户限制", status: 1, axisValue: [400, 20] },
    { uri: "授权", status: 1, axisValue: [500, 80] },
    {
      uri: "MCA提交",
      status: 0,
      axisValue: [600, 80],
      pointType: "beforeMeetingPoint",
      targetIndex: 11,
    },
    {
      uri: "Online Integration Layer",
      status: 1,
      axisValue: [700, 140],
      pointType: "meetingPoint",
    },
    { uri: "MCA", status: 1, axisValue: [800, 140] },
    { uri: "HUB Core Banking", status: 1, axisValue: [900, 140] },
    { uri: "CDP", status: 1, axisValue: [1000, 140] },
    {
      uri: "Downstream Systems",
      status: 1,
      axisValue: [1100, 140],
      pointType: "endPoint",
    },
    { uri: "API获取合格购买TCD的账户", status: 1, axisValue: [0, 200] },
    { uri: "API获取不同币种的购买额度", status: 1, axisValue: [150, 200] },
    { uri: "Wealth查询新旧资金", status: 1, axisValue: [150, 260] },
    { uri: "API获取term deposit rate", status: 1, axisValue: [300, 200] },
    { uri: "FATCA and CRS Check", status: 1, axisValue: [450, 200] },
    {
      uri: "提交申购申请",
      status: 1,
      axisValue: [600, 200],
      pointType: "beforeMeetingPoint",
      targetIndex: 11,
    },
  ];

  // var xn = 13;
  // var ynj = [0, 100, 200, 300, 300, 400, 500, 600, 700, 800, 900, 1000, 1100]
  // var yno = [1600, 1400, 1200, 1000, 800, 600, 400, 200]
  const getGraphLabelStyle = (index) => {
    if (index === 1 || index === 4 || index === 6 || index === 8) {
      return { position: "right", width: 300, distance: 10 };
    }
    if (index === 17) {
      return { position: "top", width: 150, distance: 5 };
    }
    if (index === 18) {
      return { position: "bottom", width: 160, distance: 10 };
    }
    return { position: "bottom", width: 80, distance: 10 };
  };

  var data = apis.map((el, key) => {
    // let rn = Math.floor(key / xn);

    return {
      name: el.uri,
      draggable: false,
      value: el.axisValue, // 偶数行
      // value: key === 4 ? [ynj[key % xn], 20 * (rn + 1)] : [ynj[key % xn], 100 * (rn + 1)], // 偶数行
      // value: ((rn + 1) % 2 !== 0) ?
      //     [ynj[key % xn], 100 * (rn + 1)] : // 奇数行
      //     [yno[key % xn], 100 * (rn + 1)], // 偶数行
      itemStyle:
        el.status === 1
          ? { color: "#52c41a" }
          : {
              color: "#f5222d",
              borderColor: "#f5222d",
              borderWidth: 1,
              shadowBlur: 10,
              shadowColor: "#f5222d",
            },
      label: {
        show: true, //控制非高亮时节点名称是否显示
        position: getGraphLabelStyle(key)?.position,
        fontSize: 14,
        width: getGraphLabelStyle(key)?.width,
        overflow: "break",
        distance: getGraphLabelStyle(key)?.distance,
      },
    };
  });

  var links = apis.map((el, key) => {
    if (el?.pointType !== "endPoint") {
      if (key === 1 || key === 4 || key === 6 || key === 8 || key === 18) {
        return {
          source: apis[key - 1].uri,
          value: "",
          target: apis[key + 1].uri,
        };
      } else if (key === 0 || key === 3 || key === 7 || key === 17) {
        return {
          source: el.uri,
          value: "",
          target: apis[key + 1].uri,
          lineStyle: {
            curveness: 0.1,
          },
        };
      } else if (el?.pointType === "beforeMeetingPoint") {
        return {
          source: el.uri,
          value: "",
          target: apis[el?.targetIndex].uri,
        };
      } else {
        return {
          source: el.uri,
          value: "",
          target: apis[key + 1].uri,
        };
      }
    } else {
      return {};
    }
  });

  var options = {
    title: [
      {
        text: "TCD申购流程图",
        x: "50%",
        y: "1%",
        textAlign: "center",
        textBaseline: "middle",
        textStyle: {
          fontSize: 16,
        },
      },
      {
        text: `各节点错误率`,
        x: "25%",
        y: "51%",
        textAlign: "center",
        textBaseline: "middle",
        textStyle: {
          fontSize: 16,
        },
      },
      {
        text: `各节点时间占比`,
        x: "75%",
        y: "51%",
        textAlign: "center",
        textBaseline: "middle",
        textStyle: {
          fontSize: 16,
        },
      },
    ],
    legend: [
      {
        // data: ['MCA查客户信息', 'HUB查客户证件', 'Wealth查新旧资金', 'MCA查起存条件', '录入Vof Rate', 'HUB查客户限制', '录入Vof Rate', '授权', 'MCA提交', 'Online Integration Layer', 'MCA', 'HUB Core Banking', 'CDP', 'Downstream Systems'],
        width: "90%",
        align: "auto",
        itemGap: 20,
        bottom: "0%",
      },
    ],
    //饼图配置
    dataset: [
      {
        source: [
          ["Step", "ErrorRate", "TimeRate"],
          ["MCA查客户信息", 15, 15],
          ["HUB查客户证件", 15, 15],
          ["输入资料显示产品信息", 15, 15],
          ["输入申购金额", 15, 15],
          ["Wealth查新旧资金", 14, 15],
          ["MCA查起存条件", 13, 14],
          ["录入Vof Rate", 12, 10],
          ["输入转出账户", 12, 10],
          ["HUB查客户限制", 11, 9],
          ["授权", 10, 8],
          ["MCA提交", 50, 60],
          ["Online Integration Layer", 9, 6],
          ["MCA", 8, 4],
          ["HUB Core Banking", 7, 4],
          ["CDP", 7, 3],
          ["Downstream Systems", 6, 3],
          ["API获取合格购买TCD的账户", 5, 2],
          ["API获取不同币种的购买额度", 2, 2],
          ["Wealth查询新旧资金", 2, 5],
          ["API获取term deposit rate", 2, 2],
          ["FATCA and CRS Check", 2, 2],
          ["提交申购申请", 2, 2],
        ],
      },
    ],
    // 流程图配置
    grid: [
      {
        x: 100,
        y: 20,
        width: "95%",
        height: "95%",
        tooltip: {
          trigger: "item",
          formatter: "{a}",
        },
      },
    ],
    tooltip: {
      trigger: "axis",
    },
    xAxis: [
      { gridIndex: 0, type: "value", show: false },
      { gridIndex: 0, type: "value", show: false },
    ],
    yAxis: [
      {
        gridIndex: 0,
        type: "category",
        data: [""],
        axisTick: { show: false },
        axisLine: { show: false },
      },
      {
        gridIndex: 0,
        show: false,
        type: "value",
        inverse: true,
        max: 600,
      },
    ],
    axisPointer: {
      label: {
        backgroundColor: "#777",
      },
    },

    graphic: [
      {
        type: "text",
        left: 20,
        top: 100,
        z: 100,
        style: {
          fill: "#5ab1ef",
          text: "Teller前端\n起始节点",
          font: "bold 12px Microsoft YaHei",
          textAlign: "center",
        },
      },
      {
        type: "text",
        left: 20,
        top: 250,
        z: 100,
        style: {
          fill: "#5ab1ef",
          text: "Mobile前端\n起始节点",
          font: "bold 12px Microsoft YaHei",
          textAlign: "center",
        },
      },
      {
        type: "text",
        left: echartsSize(1170),
        top: 170,
        z: 100,
        style: {
          fill: "#5ab1ef",
          text: "后端起始节点",
          font: "bold 12px Microsoft YaHei",
          textAlign: "center",
        },
      },
    ],

    series: [
      {
        type: "graph",
        coordinateSystem: "cartesian2d", // 使用二维的直角坐标系
        legendHoverLink: false,
        nodeScaleRatio: false,
        symbol: "circle", // 节点显示形状
        symbolSize: 20, // 节点大小
        edgeSymbol: ["none", "arrow"], // 线两边的标记
        symbolOffset: [0, 0],
        edgeSymbolSize: [2, 6], // 标记大小
        roam: false, // 关闭鼠标缩放
        itemStyle: {
          label: {
            show: true,
            textStyle: {
              color: "#333",
            },
          },
          nodeStyle: {
            brushType: "both",
            borderColor: "rgba(255,215,0,0.4)",
            borderWidth: 1,
          },
        },
        lineStyle: {
          opacity: 1,
          curveness: 0,
          type: "dashed",
          width: 1,
        },
        tooltip: {
          formatter: "{b}",
        },
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: data,
        links: [
          ...links,
          {
            source: "Wealth查询新旧资金",
            value: "",
            target: "API获取不同币种的购买额度",
            lineStyle: {
              curveness: 0.1,
            },
          },
          {
            source: "HUB查客户证件",
            value: "",
            target: "MCA查客户信息",
            lineStyle: {
              curveness: 0.1,
            },
          },
          {
            source: "Wealth查新旧资金",
            value: "",
            target: "输入申购金额",
            lineStyle: {
              curveness: 0.1,
            },
          },
          {
            source: "HUB查客户限制",
            value: "",
            target: "输入转出账户",
            lineStyle: {
              curveness: 0.1,
            },
          },
        ],
      },
      //饼图
      {
        type: "pie",
        label: {
          formatter: "{b} ({d}%)",
        },
        radius: 100,
        center: ["25%", "70%"],
        encode: {
          itemName: "Step",
          value: "ErrorRate",
        },
        emphasis: {
          // 高亮样式
          scaleSize: 20,
        },
        itemStyle: {
          color: (e) => {
            const cuHighLightIndexItem = highLightIndexItem.current;
            const colorList = [
              "#5ab1ef",
              "#b6a2de",
              "#2ec7c9",
              "#ffb980",
              "#d87a80",
              "#8d98b3",
              "#e5cf0d",
              "#97b552",
              "#95706d",
              "#dc69aa",
              "#07a2a4",
              "#9a7fd1",
              "#f5994e",
              "#c14089",
              "#26c0c0",
              "#f0805a",
              "#60c0dd",
              "#9bca63",
              "#27727b",
              "#d0648a",
              "#001852",
              "#ff6347",
            ];
            return e?.dataIndex === cuHighLightIndexItem?.itemIndex &&
              !cuHighLightIndexItem?.itemStatus
              ? "#f5222d"
              : colorList[e?.dataIndex];
          },
        },
        tooltip: {
          trigger: "item",
          formatter: (args) => {
            return `${args.data[0]} ${args.data[1]}(${args.percent}%)`;
          },
        },
      },
      {
        type: "pie",
        label: {
          formatter: "{b} ({d}%)",
        },
        radius: [60, 100],
        center: ["75%", "70%"],
        encode: {
          itemName: "Step",
          value: "TimeRate",
        },
        emphasis: {
          // 高亮样式
          scaleSize: 20,
        },
        itemStyle: {
          color: (e) => {
            const cuHighLightIndexItem = highLightIndexItem.current;
            const colorList = [
              "#5ab1ef",
              "#b6a2de",
              "#2ec7c9",
              "#ffb980",
              "#d87a80",
              "#8d98b3",
              "#e5cf0d",
              "#97b552",
              "#95706d",
              "#dc69aa",
              "#07a2a4",
              "#9a7fd1",
              "#f5994e",
              "#c14089",
              "#26c0c0",
              "#f0805a",
              "#60c0dd",
              "#9bca63",
              "#27727b",
              "#d0648a",
              "#001852",
              "#ff6347",
            ];
            return e?.dataIndex === cuHighLightIndexItem?.itemIndex &&
              !cuHighLightIndexItem?.itemStatus
              ? "#f5222d"
              : colorList[e?.dataIndex];
          },
        },
        tooltip: {
          trigger: "item",
          formatter: (args) => {
            return `${args.data[0]} ${args.data[2]}(${args.percent}%)`;
          },
        },
      },
    ],
  };

  const onChartClick = (params) => {
    click_type.current = false;
    setTimeout(check, 200);
    function check() {
      if (click_type.current) return;
      console.log("%c Line:258 🍒 params", "color:#465975", params);
      if (params.seriesType === "graph") {
        const graphItemIndex = params?.dataIndex;
        const myChart = chartRef.current.getEchartsInstance();
        const curHighLightIndexItem = highLightIndexItem.current;
        // 取消之前高亮的图形
        if (!isNull(curHighLightIndexItem)) {
          myChart.dispatchAction({
            type: "downplay",
            seriesIndex: 1,
            dataIndex: curHighLightIndexItem?.itemIndex,
          });
          myChart.dispatchAction({
            type: "downplay",
            seriesIndex: 2,
            dataIndex: curHighLightIndexItem?.itemIndex,
          });
        }
        // 高亮当前图形
        myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 1,
          dataIndex: graphItemIndex,
        });
        myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 2,
          dataIndex: graphItemIndex,
        });
        highLightIndexItem.current = {
          itemIndex: graphItemIndex,
          itemStatus: params.color === "#f5222d" ? 0 : 1,
        };
        myChart.setOption({});
      }
    }
  };

  const onChartDblclick = (params) => {
    click_type.current = true;
    if (params.seriesType === "pie") {
      const pieItemIndex = params?.dataIndex;
      const myChart = chartRef.current.getEchartsInstance();
      const curHighLightIndexItem = highLightIndexItem.current;
      if (pieItemIndex === curHighLightIndexItem.itemIndex) {
        // 取消之前高亮的图形
        if (!isNull(curHighLightIndexItem)) {
          myChart.dispatchAction({
            type: "downplay",
            seriesIndex: 1,
            dataIndex: curHighLightIndexItem?.itemIndex,
          });
          myChart.dispatchAction({
            type: "downplay",
            seriesIndex: 2,
            dataIndex: curHighLightIndexItem?.itemIndex,
          });
        }
        highLightIndexItem.current = null;
        myChart.setOption({});
      }
    }
  };

  const onEvents = {
    click: onChartClick,
    dblclick: onChartDblclick,
  };

  return (
    <>
      <ReactECharts
        ref={chartRef}
        option={options}
        style={{ height: 800 }}
        onEvents={onEvents}
      />
    </>
  );
});

export default Chart4;
